import os

from jinja2 import Template, FileSystemLoader, Environment
from pywebio.output import put_error, put_text


class java_template:
    def __init__(self, ding_msg, docker_name, extra_tag_flag, extra_tag_name, deploy_name, namespace, deploy_env,
                 extra_ingress_flag, domain_test, prefix_test, domain_prod, prefix_prod):
        self.ding_msg = ding_msg
        self.docker_name = docker_name
        self.extra_tag_flag = extra_tag_flag
        self.extra_tag_name = extra_tag_name
        self.deploy_name = deploy_name
        self.namespace = namespace
        self.deploy_env = deploy_env
        self.extra_ingress_flag = extra_ingress_flag
        self.domain_test = domain_test
        self.prefix_test = prefix_test
        self.domain_prod = domain_prod
        self.prefix_prod = prefix_prod

    def check_param(self):
        if self.extra_tag_flag is True and self.extra_tag_name == '':
            put_error('请输入额外Tag名')
            return False
        if self.extra_ingress_flag is True and \
                self.domain_test == '' and \
                self.prefix_test == '' and \
                self.domain_prod == '' and \
                self.prefix_prod == '':
            put_error('请输入入口相关参数')
            return False
        else:
            return True

    def render_template(self):
        if self.check_param() is False:
            return
        j2_loader = FileSystemLoader('./templates')
        env = Environment(loader=j2_loader)
        j2_tmpl = env.get_template('ingress.j2')
        os.mkdir(path='temp/' + self.deploy_name)
        j2_tmpl.stream(
            app='vue',
            ingress_name=self.deploy_name,
            namespace=self.namespace,
            kubesphere_description=self.ding_msg,
            domain=self.domain_prod,
            path=self.prefix_prod,
            svc_name=self.deploy_name,
        ).dump('ingress.yaml')
        result = j2_tmpl.render(
            app='vue',
            ingress_name=self.deploy_name,
            namespace=self.namespace,
            kubesphere_description=self.ding_msg,
            domain=self.domain_prod,
            path=self.prefix_prod,
            svc_name=self.deploy_name,
        )
        print(result)
        put_text(result)
        